/*
 *  一、优惠券分类： 
 * 	1. 新人优惠券
 *  2. 全场优惠券 
 * 	3. 单品优惠券
 * 	4. 品类优惠券
 *  二、优惠券属性
 * 	1. 优惠券 条件  满多少
 * 	2. 优惠券 优惠金额
 *  3. 优惠券期限
 */

var express = require('express');
var router = express.Router();
var request = require('request');

var CommonJS = require('../../../common/common');
var DBConfig = require('../../../db/dbconfig');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig.mysql2);
var db = require('../../../db/mysql/pool');

//领券中心
router.get('/jkyx/coupon/list',function(req,res,next){
    pool.getConnection(function(err, connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        connection.query(DBConfig.getValidCoupon,[CommonJS.getNowFormatDate(),CommonJS.getNowFormatDate(),2],function(err, result){
            connection.release();
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '查询失败',
                    status:'102',
                    err: err
                }));
            }else{ 
                let newArray = [];
                result.forEach((value,index) => {
                    let data = {}; 
                    data.id = Number(value.id);
                    data.name = value.name;
                    data.quantity = value.quantity;
                    data.person_limit = value.person_limit;
                    data.receive_num = value.receive_num;
                    data.valid_start = CommonJS.getNowFormatDateDay(value.valid_start);
                    data.valid_end = CommonJS.getNowFormatDateDay(value.valid_end);
                    data.rule = JSON.parse(value.param);
                    newArray[index] = data;
                });
                res.end(JSON.stringify({
                    status:100,
                    data:newArray
                }));
            }
        });
    });
});

//用户领取优惠券(领券中心)
router.get('/jkyx/coupon/receive',function(req,res,next){
    let param = req.query || '';
    if(!param.account_id)
    {
        res.end(JSON.stringify({
            status:102,
            msg:'无权限访问'
        }));
    }
    //加一个已领取提示
    pool.getConnection(function(err,connection){
        if(err){
			res.end(JSON.stringify({
     			msg: '数据库连接失败',
     			status:'101'
     		}));
        }
        connection.query(DBConfig.getCouponNum,[param.coupon_id,param.coupon_id,param.account_id],function(err, result){
            if(err)
            {
                res.end(JSON.stringify({
                    msg: '查询失败',
                    status:'102',
                    err: err
                }));
            }else{
                let quantity = result[0][0].quantity;
                let receive_num = result[0][0].receive_num;
                let personLimit = result[0][0].person_limit;
                let hasReceive = result[1][0].total;
                if(hasReceive >= personLimit)
                {
                    return res.end(JSON.stringify({
                        msg: '超过领取次数',
                        status:102                                
                    }));
                }
                if(quantity <= receive_num)
                {
                    res.end(JSON.stringify({
                        msg: '该优惠券已被领取完',
                        status:102                                
                    }));
                }else{
                    connection.query(DBConfig.receiveCoupon,[param.coupon_id,param.account_id,1,CommonJS.getNowFormatDate()],function(err,result){
                        if(err)
                        {
                            res.end(JSON.stringify({
                                msg: '查询失败',
                                status:'102',
                                err: err
                            }));
                        }else{
                            connection.query(DBConfig.updateCouponNumber,[param.coupon_id],function(err, result){
                                connection.release();
                                if(err)
                                {
                                    res.end(JSON.stringify({
                                        msg: '领取失败',
                                        status:'102',
                                        err: err
                                    }));
                                }else{
                                    res.end(JSON.stringify({
                                        msg: '领取成功',
                                        status:100
                                    }));
                                }
                            });
                        }
                    });
                    
                }
            }
        });
        
    });
});

//用户优惠券列表
router.get('/jkyx/user/coupon-list',function(req,res,next){
    let param = req.query;
    let type = param.type;//1可使用，0过期,2已使用
    if(!param.account_id)
    {
        res.end(JSON.stringify({
            msg: '请求失败，没有查到用户',
            status:'103'
        })); 
    }
    pool.getConnection(function(err, connection){
        if(err)
        {
            res.end(JSON.stringify({
                msg: '数据库连接失败',
                status:'101'
            })); 
        }else{
            switch(Number(type))
            {
                case 0:
                  userCouponUnValidList(res,req,connection,param);
                  break;
                case 1:
                  userCouponValidList(res,req,connection,param);
                   break;
                case 2:
                  hasUsedCouponList(res,req,connection,param);
                   break;
                default:
                res.end(JSON.stringify({
                    msg: '请求失败，无效的类型',
                    status:'103'
                })); 
                   break;     
            }
            
        }
    });
});


function userCouponUnValidList(res,req,connection,param)
{
    connection.query(DBConfig.userCouponEndCount,[param.account_id,CommonJS.getNowFormatDate()],function(err, result){
        if(err){
			res.end(JSON.stringify({
                msg: '查询失败',
                status:'102',
                err: err
            }));
        }
        var totalCount = result[0].totalCount,page = Number(req.query.page),limit = req.query.limit || 20;
        var totalPage = Math.ceil(totalCount/limit);
        if(page)
        {
            var limitStart = Number(page-1)*limit,limitEnd = page*limit;
        }else
        {
            var limitStart = 0,limitEnd = totalCount;
        }
        connection.query(DBConfig.userCouponEnd,[param.account_id,CommonJS.getNowFormatDate(),limitStart,limitEnd],function(err, result){
            connection.release();
            let newArray = [];
            result.forEach((data,index)=>{
                data.id = Number(data.id);
                data.valid_end = CommonJS.getNowFormatDateDay(data.valid_end);
                data.valid_start = CommonJS.getNowFormatDateDay(data.valid_start);
                data.param = JSON.parse(data.param);
                newArray[index] = data;
            });
            res.end(JSON.stringify({
                status:100,
                type:'unvalid',//过期
                data:newArray
            }));
        });
    });
    
}

function userCouponValidList(res,req,connection,param)
{
    connection.query(DBConfig.userCouponListCount,[param.account_id,CommonJS.getNowFormatDate(),CommonJS.getNowFormatDate(),1],function(err, result){
        if(err){
			res.end(JSON.stringify({
                msg: '查询失败',
                status:'102',
                err: err
            }));
        }
        var totalCount = result[0].totalCount,page = Number(req.query.page),limit = req.query.limit || 20;
        var totalPage = Math.ceil(totalCount/limit);
        if(page)
        {
            var limitStart = Number(page-1)*limit,limitEnd = page*limit;
        }else
        {
            var limitStart = 0,limitEnd = totalCount;
        }
        connection.query(DBConfig.userCouponList,[param.account_id,CommonJS.getNowFormatDate(),CommonJS.getNowFormatDate(),1,limitStart,limitEnd],function(err, result){
            connection.release();
            let newArray = [];
            result.forEach((data,index)=>{
                data.id = Number(data.id);
                data.valid_end = CommonJS.getNowFormatDateDay(data.valid_end);
                data.valid_start = CommonJS.getNowFormatDateDay(data.valid_start);
                data.bind_time = CommonJS.getNowFormatDateDay(data.bind_time);
                data.param = JSON.parse(data.param);
                newArray[index] = data;
            });
            res.end(JSON.stringify({
                status:100,
                type:'valid',//过期
                data:newArray
            }));
        });
    });
}

function hasUsedCouponList(res,req,connection,param)
{
    connection.query(DBConfig.userHasUsedCouponCount,[param.account_id,2],function(err, result){
        if(err){
			res.end(JSON.stringify({
                msg: '查询失败',
                status:'102',
                err: err
            }));
        }
        var totalCount = result[0].totalCount,page = Number(req.query.page),limit = req.query.limit || 20;
        var totalPage = Math.ceil(totalCount/limit);
        if(page)
        {
            var limitStart = Number(page-1)*limit,limitEnd = page*limit;
        }else
        {
            var limitStart = 0,limitEnd = totalCount;
        }
        connection.query(DBConfig.userHasUsedCoupon,[param.account_id,2,limitStart,limitEnd],function(err, result){
            connection.release();
            let newArray = [];
            result.forEach((data,index)=>{
                data.id = Number(data.id);
                data.valid_end = CommonJS.getNowFormatDateDay(data.valid_end);
                data.valid_start = CommonJS.getNowFormatDateDay(data.valid_start);
                data.bind_time = CommonJS.getNowFormatDateDay(data.bind_time);
                data.param = JSON.parse(data.param);
                newArray[index] = data;
            });
            res.end(JSON.stringify({
                status:100,
                type:'used',//已使用
                data:newArray
            }));
        });
    });
}


router.get('/jkyx/coupon/list-test',function(req,res,next){
    test(req,res,next);
});

async function test(req,res,next)
{
    new Promise();
    let kk = await db.query(DBConfig.getCoupon,[5],async function(result){
        if(result.statu == 100)
        {
            return 222;
        }else{
            res.end(JSON.stringify({
                msg:'操作失败',
                status:102
            }));
        }
        
    });
    console.log(kk);
}

//获取某个商品优惠券集合
router.get('/jkyx/coupon-goods/list', function(req,res,next){
    var param = req.query;
    let goods_id = param.goods_id || '';
    let now = CommonJS.getNowFormatDate();
    db.query(DBConfig.getGoodsCoupon,[now,now,1,1,2,goods_id],function(result){
        //result.release();
        if(result.status == 100)
        {
           let newArray = [];
           let datas = result.data.rows; 
           datas.forEach((data,i)=>{
               data.id = Number(data.id);
               data.param = JSON.parse(data.param);
               data.valid_start = CommonJS.getNowFormatDateDay(data.valid_start);
               data.valid_end = CommonJS.getNowFormatDateDay(data.valid_end);
               newArray[i] = data;
           });
           res.end(JSON.stringify({
               status:100,
               data:newArray
           }));
        }else{
            res.end(JSON.stringify({
                status:102,
                msg:'操作错误'
            }));
        }
    });
});


//领取商品优惠券
router.get('/jkyx/coupon-goods/receive',function(req,res,next){
    let param = req.query || '';
    if((!param.account_id) || (!param.coupon_id))
    {
        throw Error("无权限操作");
    }
    
    db.query('select * from coupon where id = ?',[param.coupon_id],function(result){
        if(result.status != 100)
        {
            res.end(JSON.stringify({
                status:102,
                msg:'操作错误'
            }));
            return;
        }
        //result.release();
        let coupon = result.data.rows[0];
        let quantity = coupon.quantity,receive_num = coupon.receive_num;
        if(quantity <= receive_num)
        {
            res.end(JSON.stringify({
                status:102,
                msg:'该优惠券已经被领取完毕'
            }));
            return;
        }
        db.query('select count(*) as total from coupon_bind where coupon_id = ? and account_id = ?',[param.coupon_id,param.account_id],function(result){
            //result.release();
            let total = result.data.rows[0].total;
            if(total >=1)
            {
                res.end(JSON.stringify({
                    status:102,
                    msg:'您已经领取过该券'
                }));

            }else{
                pool.getConnection(function(err,connection){
                    if(err)
                    {
                        res.end(JSON.stringify({
                            status:102,
                            msg:'操作错误'
                        }));
                    }else{
                        connection.query(DBConfig.receiveGoodsCoupon,[param.coupon_id,param.account_id,1,CommonJS.getNowFormatDate(),param.coupon_id],function(err,result){
                            connection.release();
                            if(err)
                            {
                                res.end(JSON.stringify({
                                    status:102,
                                    msg:'领取失败'
                                }));
                            }else{
                                res.end(JSON.stringify({
                                    status:100,
                                    msg:'领取成功'
                                }));
                            }
                        });
                    }
                });
            }
        });

    });
    
});


router.get('/jkyx/pc/coupon/use-coupon',function(req,res,next){
    var param = req.query || '';
    let couponBindId = Number(param.coupon_id) || '';
    let type = Number(param.type) || 2;//2为使用，1为返还
    if(!couponBindId)
    {
        throw Error("缺少优惠券");
    }
    db.query(DBConfig.useCoupon,[type,couponBindId],function(result){
        if(result.status == 100)
        {
            res.end(JSON.stringify({
            status:100,
            msg:'操作成功'
        }));
        }else{ 
            res.end(JSON.stringify({
                status:102,
                msg:'操作错误'
            }));
        }
    });
});


module.exports = router;